package org.csu.small.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import org.csu.alipay.demo.trade.model.GoodsDetail;
import org.csu.alipay.demo.trade.config.Configs;
import org.csu.alipay.demo.trade.model.builder.AlipayTradePrecreateRequestBuilder;
import org.csu.alipay.demo.trade.service.AlipayTradeService;
import org.csu.alipay.demo.trade.service.impl.AlipayTradeServiceImpl;
import org.csu.alipay.demo.trade.model.result.AlipayF2FPrecreateResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.beust.jcommander.internal.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.csu.alipay.demo.trade.utils.ZxingUtils;
import org.csu.small.common.UniformResponse;
import org.csu.small.common.Constant;
import org.csu.small.configuration.AlipayConfig;
import org.csu.small.entity.*;
import org.csu.small.persistence.*;
import org.csu.small.service.IOrderService;
import org.csu.small.utils.BigDecimalUtil;
import org.csu.small.utils.FTPUtil;
import org.csu.small.utils.PropertiesUtil;
import org.csu.small.utils.QiniuCloudUtil;
import org.csu.small.vo.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @author SongYaolun
 * @version 1.0
 * @date 2020/6/27 11:11
 */
@Service("orderService")
@Transactional
public class OrderServiceImpl implements IOrderService {
    private static final Logger logger = LoggerFactory.getLogger(OrderServiceImpl.class);

    private static AlipayTradeService tradeService;

    static {

        /** 一定要在创建AlipayTradeService之前调用Configs.init()设置默认参数
         *  Configs会读取classpath下的zfbinfo.properties文件配置信息，如果找不到该文件则确认该文件是否在classpath目录
         */
        Configs.init("zfbinfo.properties");

        /** 使用Configs提供的默认参数
         *  AlipayTradeService可以使用单例或者为静态成员对象，不需要反复new
         */
        tradeService = new AlipayTradeServiceImpl.ClientBuilder().build();
    }

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private PayInfoMapper payInfoMapper;
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ShippingMapper shippingMapper;

    /**
     * 前台部分
     */

    @Override
    public UniformResponse<OrderVo> createOrder(Integer userId, Integer shippingId){

        List<Cart> cartList = cartMapper.selectList(Wrappers.<Cart>query().eq("user_id",userId));

        //计算这个订单的总价
        UniformResponse UniformResponse = this.getCartOrderItem(userId, cartList);
        if (!UniformResponse.isSuccess()) {
            return UniformResponse;
        }
        List<OrderItem> orderItemList = (List<OrderItem>) UniformResponse.getData();
        BigDecimal payment = this.getOrderTotalPrice(orderItemList);


        //生成订单
        Order order = this.assembleOrder(userId, shippingId, payment);
        if (order == null) {
            return UniformResponse.createForErrorMessage("生成订单错误");
        }
        if (CollectionUtils.isEmpty(orderItemList)) {
            return UniformResponse.createForErrorMessage("购物车为空");
        }
        for (OrderItem orderItem : orderItemList) {
            orderItem.setOrderNo(order.getOrderNo());
        }

        //mybatis 批量插入
        for(OrderItem orderItem : orderItemList){
            orderItemMapper.insert(orderItem);
        }
        //生成成功,我们要减少我们产品的库存
        this.reduceProductStock(orderItemList);
        //清空一下购
        this.cleanCart(cartList);

        //返回给前端数据
        OrderVo orderVo = assembleOrderVo(order, orderItemList);
        return UniformResponse.createForSuccess(orderVo);
    }

    @Override
    public UniformResponse<OrderVo> getOrderDetail(BigInteger orderNo){

        Order order = orderMapper.selectOne(Wrappers.<Order>query().eq("order_no",orderNo));
        if (order != null) {
            List<OrderItem> orderItemList = orderItemMapper.selectList(Wrappers.<OrderItem>query().eq("order_no",orderNo));
            OrderVo orderVo = assembleOrderVo(order, orderItemList);
            return UniformResponse.createForSuccess(orderVo);
        }
        return UniformResponse.createForErrorMessage("没有找到该订单");
    }


    @Override
    public UniformResponse<String> confirm(BigInteger orderNo){
        Order order = orderMapper.selectOne(Wrappers.<Order>query().eq("order_no",orderNo));
        if (order == null) {
            return UniformResponse.createForErrorMessage("该用户此订单不存在");
        }
        if(order.getStatus() != Constant.OrderStatus.SEND.getCode()){
            return UniformResponse.createForErrorMessage("尚未发货");
        }
        order.setEndTime(LocalDateTime.now());
        order.setStatus(Constant.OrderStatus.SUCCEEDED.getCode());

        UpdateWrapper<Order> wrapper = new UpdateWrapper<>();
        wrapper.eq("order_no",orderNo);

        int rows = orderMapper.update(order,wrapper);
        if(rows > 0){
            return UniformResponse.createForSuccess("订单已确认收货",order.getEndTime().toString());
        }
        return UniformResponse.createForError();
    }

    @Override
    public UniformResponse<String> cancel(BigInteger orderNo){
        Order order = orderMapper.selectOne(Wrappers.<Order>query().eq("order_no",orderNo));
        if (order == null) {
            return UniformResponse.createForErrorMessage("该用户此订单不存在");
        }
        if (order.getStatus() != Constant.OrderStatus.NONPAYMENT.getCode()) {
            return UniformResponse.createForErrorMessage("已付款,无法取消订单");
        }

        order.setCloseTime(LocalDateTime.now());
        order.setStatus(Constant.OrderStatus.CANCEL.getCode());

        UpdateWrapper<Order> wrapper = new UpdateWrapper<>();
        wrapper.eq("order_no",orderNo);

        int row = orderMapper.update(order,wrapper);
        if (row > 0) {
            return UniformResponse.createForSuccess("订单已取消",order.getCloseTime().toString());
        }
        return UniformResponse.createForError();


    }

    @Override
    public UniformResponse<String> refund(BigInteger orderNo){
        Order order = orderMapper.selectOne(Wrappers.<Order>query().eq("order_no",orderNo));
        if(order.getStatus() != Constant.OrderStatus.PAYMENT.getCode()){
            return UniformResponse.createForErrorMessage("无法退款");
        }
        order.setCloseTime(LocalDateTime.now());
        order.setStatus(Constant.OrderStatus.CANCEL.getCode());
        UpdateWrapper<Order> wrapper = new UpdateWrapper<>();
        wrapper.eq("order_no",orderNo);
        int rows = orderMapper.update(order,wrapper);
        if(rows == 0){
            return UniformResponse.createForErrorMessage("订单退款失败");
        }
        return UniformResponse.createForSuccess("取消订单成功",order.getCloseTime().toString());

    }

    @Override
    public UniformResponse getUserOrderList(Integer userId, int current, int size){

        Page<Order> result = new Page<>();
        result.setCurrent(current);
        result.setSize(size);

        QueryWrapper <Order> query = new QueryWrapper<>();
        query.eq("user_id",userId);

        result = orderMapper.selectPage(result,query);

        return UniformResponse.createForSuccess("成功查询",this.assembleOrderPageVo(result));


    }

    @Override
    public UniformResponse<Object> getOrderSearch(BigInteger orderNo, String productName, int current, int size, Integer status){

        Page<Order> result = new Page<>();
        result.setCurrent(current);
        result.setSize(size);

        QueryWrapper <Order> query = new QueryWrapper<>();
        List<BigInteger> orderNoList = new ArrayList<>();

        //通过指定订单号查询
        if(!orderNo.equals(BigInteger.ZERO)){
            query.eq("order_no",orderNo);
        }
        //通过订单状态查询
        else if(!status.equals(0)){
            query.eq("status",status);
        }
        //通过订单子项中包含的商品名模糊查询
        else if(StringUtils.isNotBlank(productName)){
            productName = new StringBuilder().append("%").append(productName).append("%").toString();
            QueryWrapper<OrderItem> wrapper = new QueryWrapper<>();
            wrapper.like("product_name",productName);
            List<OrderItem> list = orderItemMapper.selectList(wrapper);
            for(OrderItem item : list){
                orderNoList.add(item.getOrderNo());
            }
            query.in("order_no",orderNoList);

        }

        result = orderMapper.selectPage(result,query);
        if(result.getSize()==0){
            return UniformResponse.createForErrorMessage("未查询到结果");
        }
        return UniformResponse.createForSuccess("成功查询",this.assembleOrderPageVo(result));

    }

    @Override
    public UniformResponse getOrderCartProduct(Integer userId) {
        OrderProductVo orderProductVo = new OrderProductVo();
        //从购物车中获取数据

        List<Cart> cartList = cartMapper.selectList(Wrappers.<Cart>query().eq("user_id",userId).eq("checked",Constant.Cart.CHECKED));
        UniformResponse serverResponse = this.getCartOrderItem(userId, cartList);
        if (!serverResponse.isSuccess()) {
            return serverResponse;
        }
        List<OrderItem> orderItemList = (List<OrderItem>) serverResponse.getData();

        List<OrderItemVo> orderItemVoList = Lists.newArrayList();

        BigDecimal payment = new BigDecimal("0");
        for (OrderItem orderItem : orderItemList) {
            payment = BigDecimalUtil.add(payment.doubleValue(), orderItem.getTotalPrice().doubleValue());
            orderItemVoList.add(assembleOrderItemVo(orderItem));
        }
        orderProductVo.setProductTotalPrice(payment);
        orderProductVo.setOrderItemVoList(orderItemVoList);
        orderProductVo.setImageHost(PropertiesUtil.getProperty("image.server.url"));
        return UniformResponse.createForSuccess(orderProductVo);
    }

    /**
     * 支付部分
     */

    /**
     * 支付接口
     *
     * @return
     */
    @Override
    public UniformResponse pay(BigInteger orderNo, String path) throws UnsupportedEncodingException {
        Map<String, String> resultMap = Maps.newHashMap();
        Order order = orderMapper.selectOne(Wrappers.<Order>query().eq("order_no",orderNo));
        if (order == null) {
            return UniformResponse.createForErrorMessage("用户没有该订单");
        }
        resultMap.put("orderNo", String.valueOf(order.getOrderNo()));


        // (必填) 商户网站订单系统中唯一订单号，64个字符以内，只能包含字母、数字、下划线，
        // 需保证商户系统端不能重复，建议通过数据库sequence生成，
        String outTradeNo = order.getOrderNo().toString();


        // (必填) 订单标题，粗略描述用户的支付目的。如“xxx品牌xxx门店当面付扫码消费”
        String subject = new StringBuilder().append("Small网上购物城扫码支付,订单号:").append(outTradeNo).toString();


        // (必填) 订单总金额，单位为元，不能超过1亿元
        // 如果同时传入了【打折金额】,【不可打折金额】,【订单总金额】三者,则必须满足如下条件:【订单总金额】=【打折金额】+【不可打折金额】
        String totalAmount = order.getPaymentPrice().toString();


        // (可选) 订单不可打折金额，可以配合商家平台配置折扣活动，如果酒水不参与打折，则将对应金额填写至此字段
        // 如果该值未传入,但传入了【订单总金额】,【打折金额】,则该值默认为【订单总金额】-【打折金额】
        String undiscountableAmount = "0";


        // 卖家支付宝账号ID，用于支持一个签约账号下支持打款到不同的收款账号，(打款到sellerId对应的支付宝账号)
        // 如果该字段为空，则默认为与支付宝签约的商户的PID，也就是appid对应的PID
        String sellerId = "";

        // 订单描述，可以对交易或商品进行一个详细地描述，比如填写"购买商品2件共15.00元"
        String body = new StringBuilder().append("订单").append(outTradeNo).append("购买商品共").append(totalAmount).append("元").toString();


        // 商户操作员编号，添加此参数可以为商户操作员做销售统计
        String operatorId = "test_operator_id";

        // (必填) 商户门店编号，通过门店号和商家后台可以配置精准到门店的折扣信息，详询支付宝技术支持
        String storeId = "test_store_id";

        // 支付超时，定义为120分钟
        String timeoutExpress = "120m";

        // 商品明细列表，需填写购买商品详细信息，
        List<GoodsDetail> goodsDetailList = new ArrayList<>();

        List<OrderItem> orderItemList = orderItemMapper.selectList(Wrappers.<OrderItem>query().eq("order_no",orderNo));;
        for (OrderItem orderItem : orderItemList) {
            GoodsDetail goods = GoodsDetail.newInstance(orderItem.getProductId().toString(), orderItem.getProductName(),
                    BigDecimalUtil.mul(orderItem.getCurrentUnitPrice().doubleValue(), new Double(100).doubleValue()).longValue(),
                    orderItem.getQuantity());
            goodsDetailList.add(goods);
        }

        // 创建扫码支付请求builder，设置请求参数
        AlipayTradePrecreateRequestBuilder builder = new AlipayTradePrecreateRequestBuilder()
                .setSubject(subject).setTotalAmount(totalAmount).setOutTradeNo(outTradeNo)
                .setUndiscountableAmount(undiscountableAmount).setSellerId(sellerId).setBody(body)
                .setOperatorId(operatorId).setStoreId(storeId)
                .setTimeoutExpress(timeoutExpress)
                .setNotifyUrl(PropertiesUtil.getProperty("alipay.callback.url"))//支付宝服务器主动通知商户服务器里指定的页面http路径,根据需要设置
                .setGoodsDetailList(goodsDetailList);


        AlipayF2FPrecreateResult result = tradeService.tradePrecreate(builder);
        switch (result.getTradeStatus()) {
            case SUCCESS:
                logger.info("支付宝预下单成功: )");

                logger.info(path);
                AlipayTradePrecreateResponse response = result.getResponse();

                File folder = new File(path);
                if (!folder.exists()) {
                    folder.setWritable(true);
                    folder.mkdirs();
                    logger.info("文件创建完毕！");
                }

                //需要修改为运行机器上的路径
                //细节细节细节，我们获取的path后面还没有"/"的，注意加上，qr-%s.png是后缀名
                String qrPath = String.format(path + "/qr-%s.png", response.getOutTradeNo());//二维码path
                String qrFileName = String.format("qr-%s.png", response.getOutTradeNo());//二维码文件名
                ZxingUtils.getQRCodeImge(response.getQrCode(), 256, qrPath);

                logger.info("qrFileName:"+qrFileName);
                logger.info("qrPath:"+qrPath);
                if(QiniuCloudUtil.upload(path+"/"+qrFileName,qrFileName,true)){
                    logger.info("成功上传！");

                }


                String qrUrl = QiniuCloudUtil.fileUrl(qrFileName);
                resultMap.put("qrUrl", qrUrl);

                return UniformResponse.createForSuccess(resultMap);

            case FAILED:
                logger.error("支付宝预下单失败!!!");
                return UniformResponse.createForErrorMessage("支付宝预下单失败!!!");

            case UNKNOWN:
                logger.error("系统异常，预下单状态未知!!!");
                return UniformResponse.createForErrorMessage("系统异常，预下单状态未知!!!");

            default:
                logger.error("不支持的交易状态，交易返回异常!!!");
                return UniformResponse.createForErrorMessage("不支持的交易状态，交易返回异常!!!");
        }

    }



    @Override
    public UniformResponse queryOrderPayStatus(BigInteger orderNo) {
        Order order = orderMapper.selectOne(Wrappers.<Order>query().eq("order_no",orderNo));
        if (order == null) {
            return UniformResponse.createForErrorMessage("用户没有该订单");
        }
        if (order.getStatus() >= Constant.OrderStatus.PAYMENT.getCode()) {
            return UniformResponse.createForSuccess();
        }
        return UniformResponse.createForError();
    }


    @Override
    public UniformResponse aliCallback(Map<String, String> params) {
        //订单号
        Long orderNo = Long.parseLong(params.get("out_trade_no"));
        String tradeNo = params.get("trade_no");
        String tradeStatus = params.get("trade_status");

        //判断我们是不是存在这个订单
        Order order = orderMapper.selectOne(Wrappers.<Order>query().eq("order_no",orderNo));
        if (order == null) {
            return UniformResponse.createForErrorMessage("非Able商城的订单,回调忽略");
        }

        //订单状态
        if (order.getStatus() >= Constant.OrderStatus.PAYMENT.getCode()) {
            return UniformResponse.createForSuccess("支付宝重复调用");
        }

        //已付款
        if (Constant.AlipayCallback.TRADE_STATUS_TRADE_SUCCESS.equals(tradeStatus)) {
            order.setPaymentTime(LocalDateTime.now());//更新交易付款的时间
            order.setStatus(Constant.OrderStatus.PAYMENT.getCode());
            UpdateWrapper<Order> wrapper = new UpdateWrapper<>();
            wrapper.eq("order_no",orderNo);
            orderMapper.update(order,wrapper);
        }

        //组装我们的payInfo对象
        PayInfo payInfo = new PayInfo();
        payInfo.setUserId(order.getUserId());
        payInfo.setOrderNo(order.getOrderNo());//交易创建，等待买家付款
        payInfo.setPayPlatform(Constant.PayPlatformEnum.ALIPAY.getCode());
        payInfo.setPlatformNumber(tradeNo);//支付宝的交易号
        payInfo.setPlatformStatus(tradeStatus);//回调状态

        payInfoMapper.insert(payInfo);
        return UniformResponse.createForSuccess();
    }


    /**
     * 后台部分
     */

    @Override
    public UniformResponse<OrderPageVo> manageList(int current, int size) {

        Page<Order> result = new Page<>();
        result.setCurrent(current);
        result.setSize(size);

        result = orderMapper.selectPage(result,null);

        return UniformResponse.createForSuccess("成功查询",this.assembleOrderPageVo(result));

    }

    @Override
    public UniformResponse<OrderVo> manageDetail(BigInteger orderNo) {
        Order order = orderMapper.selectOne(Wrappers.<Order>query().eq("order_no",orderNo));
        if (order != null) {
            List<OrderItem> orderItemList = orderItemMapper.selectList(Wrappers.<OrderItem>query().eq("order_no",orderNo));
            OrderVo orderVo = assembleOrderVo(order, orderItemList);
            return UniformResponse.createForSuccess(orderVo);
        }
        return UniformResponse.createForErrorMessage("订单不存在");
    }

    @Override
    public UniformResponse<String> manageSendGoods(BigInteger orderNo) {
        Order order = orderMapper.selectOne(Wrappers.<Order>query().eq("order_no",orderNo));
        if (order != null) {
            if (order.getStatus() == Constant.OrderStatus.PAYMENT.getCode()) {
                order.setStatus(Constant.OrderStatus.SEND.getCode());
                order.setSendTime(LocalDateTime.now());
                UpdateWrapper<Order> wrapper = new UpdateWrapper<>();
                wrapper.eq("order_no",orderNo);
                orderMapper.update(order,wrapper);
                return UniformResponse.createForSuccessMessage("发货成功");
            }
        }
        return UniformResponse.createForErrorMessage("订单不存在");
    }


    /**
     * 各种工具类
     */

    //通过当前时间生成订单号
    public static BigInteger getOrderIdByTime() {
        Long milliSecond = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
        BigInteger tempTime = BigInteger.valueOf(milliSecond);
        BigInteger result = BigInteger.valueOf(0);
        Random random = new Random();
        for(int i=0;i<3;i++) {
            result.add(BigInteger.valueOf(random.nextInt(10)));
        }
        return result.add(tempTime);
    }

    private OrderVo assembleOrderVo(Order order, List<OrderItem> orderItemList) {
        OrderVo orderVo = new OrderVo();
        orderVo.setOrderNo(order.getOrderNo());
        orderVo.setPaymentPrice(order.getPaymentPrice());
        orderVo.setPaymentType(order.getPaymentType());
        orderVo.setPaymentTypeDesc(Constant.PaymentTypeEnum.codeOf(order.getPaymentType()).getDescription());

        orderVo.setPostage(order.getPostage());
        orderVo.setStatus(order.getStatus());
        orderVo.setStatusDesc(Constant.OrderStatus.codeOf(order.getStatus()).getDescription());

        orderVo.setShippingId(order.getShippingId());
        Shipping shipping = shippingMapper.selectById(order.getShippingId());
        if (shipping != null) {
            orderVo.setReceiverName(shipping.getAddressName());
            orderVo.setShippingVo(assembleShippingVo(shipping));
        }

        orderVo.setCreateTime(order.getCreateTime());

        if(order.getPaymentTime() != null){
            orderVo.setPaymentTime(order.getPaymentTime());
        }
        if(order.getSendTime() != null) {
            orderVo.setSendTime(order.getSendTime());
        }
        if(order.getCloseTime() != null){
            orderVo.setEndTime(order.getEndTime());

        }
        if(order.getCloseTime() != null){
            orderVo.setCloseTime(order.getCloseTime());
        }

        orderVo.setImageHost(PropertiesUtil.getProperty("image.server.url"));


        List<OrderItemVo> orderItemVoList = Lists.newArrayList();

        for (OrderItem orderItem : orderItemList) {
            OrderItemVo orderItemVo = assembleOrderItemVo(orderItem);
            orderItemVoList.add(orderItemVo);
        }
        orderVo.setOrderItemVoList(orderItemVoList);
        return orderVo;
    }

    private OrderItemVo assembleOrderItemVo(OrderItem orderItem) {
        OrderItemVo orderItemVo = new OrderItemVo();
        orderItemVo.setOrderNo(orderItem.getOrderNo());
        orderItemVo.setProductId(orderItem.getProductId());
        orderItemVo.setProductName(orderItem.getProductName());
        orderItemVo.setProductImage(orderItem.getProductImage());
        orderItemVo.setCurrentUnitPrice(orderItem.getCurrentUnitPrice());
        orderItemVo.setQuantity(orderItem.getQuantity());
        orderItemVo.setTotalPrice(orderItem.getTotalPrice());

        orderItemVo.setCreateTime(orderItem.getCreateTime());
        return orderItemVo;
    }

    private ShippingVo assembleShippingVo(Shipping shipping) {
        ShippingVo shippingVo = new ShippingVo();
        shippingVo.setReceiverName(shipping.getAddressName());
        shippingVo.setReceiverAddress(shipping.getAddressDetail());
        shippingVo.setReceiverProvince(shipping.getAddressProvince());
        shippingVo.setReceiverCity(shipping.getAddressCity());
        shippingVo.setReceiverDistrict(shipping.getAddressDistrict());
        shippingVo.setReceiverMobile(shipping.getAddressMobile());
        shippingVo.setReceiverZip(shipping.getAddressZip());
        shippingVo.setReceiverPhone(shippingVo.getReceiverPhone());
        return shippingVo;
    }

    private void cleanCart(List<Cart> cartList) {
        for (Cart cart : cartList) {
            cartMapper.deleteById(cart.getId());
        }
    }

    private UniformResponse getCartOrderItem(Integer userId, List<Cart> cartList) {
        List<OrderItem> orderItemList = Lists.newArrayList();
        if (CollectionUtils.isEmpty(cartList)) {
            return UniformResponse.createForErrorMessage("购物车为空");
        }

        //校验购物车的数据,包括产品的状态和数量
        for (Cart cartItem : cartList) {
            OrderItem orderItem = new OrderItem();
            Product product = productMapper.selectById(cartItem.getProductId());
            if (Constant.ProductStatus.ON_SALE.getCode() != product.getStatus()) {
                return UniformResponse.createForErrorMessage("产品" + product.getName() + "不是在线售卖状态");
            }

            //校验库存
            if (cartItem.getQuantity() > product.getStock()) {
                return UniformResponse.createForErrorMessage("产品" + product.getName() + "库存不足");
            }

            orderItem.setUserId(userId);
            orderItem.setProductId(product.getId());
            orderItem.setProductName(product.getName());
            orderItem.setProductImage(product.getMainImage());
            orderItem.setCurrentUnitPrice(product.getPrice());
            orderItem.setQuantity(cartItem.getQuantity());
            orderItem.setTotalPrice(product.getPrice().multiply(BigDecimal.valueOf(cartItem.getQuantity())));
            orderItemList.add(orderItem);
        }
        return UniformResponse.createForSuccess(orderItemList);
    }

    private BigDecimal getOrderTotalPrice(List<OrderItem> orderItemList) {
        BigDecimal payment = new BigDecimal("0");
        for (OrderItem orderItem : orderItemList) {
            payment = BigDecimalUtil.add(payment.doubleValue(), orderItem.getTotalPrice().doubleValue());
        }
        return payment;
    }

    private OrderPageVo assembleOrderPageVo(Page result){
        OrderPageVo orderPageVo = new OrderPageVo();
        if(result.hasPrevious()){
            orderPageVo.setHasPreviousPage(true);
            orderPageVo.setPrePage((int)result.getCurrent()-1);
        }
        if(result.hasNext()){
            orderPageVo.setHasNextPage(true);
            orderPageVo.setPrePage((int)result.getCurrent()+1);
        }
        List<OrderVo> orderVoList = assembleOrderVoList(result.getRecords(), null);
        orderPageVo.setPages((int)result.getPages());
        orderPageVo.setCurrent((int)result.getCurrent());
        orderPageVo.setSize((int)result.getSize());
        orderPageVo.setTotal((int)result.getTotal());
        orderPageVo.setOrderVoList(orderVoList);

        return orderPageVo;
    }

    private Order assembleOrder(Integer userId, Integer shippingId, BigDecimal payment) {
        Order order = new Order();
        BigInteger orderNo = this.getOrderIdByTime();
        order.setOrderNo(orderNo);
        order.setStatus(Constant.OrderStatus.NONPAYMENT.getCode());
        order.setPostage(0);
        order.setPaymentType(Constant.PaymentTypeEnum.ONLINE_PAY.getCode());
        order.setPaymentPrice(payment);

        order.setUserId(userId);
        order.setShippingId(shippingId);
        //发货时间等等
        //付款时间等等
        int rowCount = orderMapper.insert(order);
        if (rowCount > 0) {
            return order;
        }
        return null;
    }

    private List<OrderVo> assembleOrderVoList(List<Order> orderList, Integer userId) {
        List<OrderVo> orderVoList = Lists.newArrayList();
        for (Order order : orderList) {
            List<OrderItem> orderItemList = Lists.newArrayList();
            if (userId == null) {
                orderItemList = orderItemMapper.selectList(Wrappers.<OrderItem>query().eq("order_no",order.getOrderNo()));
            } else {
                orderItemList = orderItemMapper.selectList(Wrappers.<OrderItem>query().eq("user_id",userId));
            }
            OrderVo orderVo = assembleOrderVo(order, orderItemList);
            orderVoList.add(orderVo);
        }
        return orderVoList;
    }

    private void reduceProductStock(List<OrderItem> orderItemList) {
        for (OrderItem orderItem : orderItemList) {
            Product product = productMapper.selectById(orderItem.getProductId());
            product.setStock(product.getStock() - orderItem.getQuantity());
            UpdateWrapper<Product> wrapper = new UpdateWrapper<>();
            wrapper.eq("id",orderItem.getProductId());
            productMapper.update(product,wrapper);
        }
    }

    //    public UniformResponse getOrderCartProduct(Integer userId) {
//        OrderProductVo orderProductVo = new OrderProductVo();
//        //从购物车中获取数据
//
//        List<Cart> cartList = cartMapper.selectList(Wrappers.<Cart>query().eq("user_id",userId));
//        UniformResponse UniformResponse = this.getCartOrderItem(userId, cartList);
//        if (!UniformResponse.isSuccess()) {
//            return UniformResponse;
//        }
//        List<OrderItem> orderItemList = (List<OrderItem>) UniformResponse.getData();
//
//        List<OrderItemVo> orderItemVoList = Lists.newArrayList();
//
//        BigDecimal payment = new BigDecimal("0");
//        for (OrderItem orderItem : orderItemList) {
//            payment = BigDecimalUtil.add(payment.doubleValue(), orderItem.getTotalPrice().doubleValue());
//            orderItemVoList.add(assembleOrderItemVo(orderItem));
//        }
//        orderProductVo.setProductTotalPrice(payment);
//        orderProductVo.setOrderItemVoList(orderItemVoList);
//        orderProductVo.setImageHost("");
//        return UniformResponse.createForSuccess(orderProductVo);
//    }

    //    @Override
//    public UniformResponse<String> delete(BigInteger orderNo){
//        Order order = orderMapper.selectOne(Wrappers.<Order>query().eq("order_no",orderNo));
//        if(order.getStatus() != Constant.OrderStatus.CLOSED.getCode()||order.getStatus()!=Constant.OrderStatus.SUCCEEDED.getCode()){
//            return UniformResponse.createForErrorCodeMessage(Constant.dataStatus.ERROR,"无法删除订单");
//        }
//        order.setEndTime(LocalDateTime.now());
//        QueryWrapper<Order> wrapper = new QueryWrapper<>();
//        wrapper.eq("order_no",orderNo);
//        int rows = orderMapper.delete(wrapper);
//        if(rows == 0){
//            return UniformResponse.createForErrorMessage("订单删除失败");
//        }
//        return UniformResponse.createForSuccessCodeMessage(Constant.dataStatus.SUCCESS,"订单删除成功");
//
//    }

}
